﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace H2.NET.DBUtility
{
    public class PubConstant
    {
        /// <summary>
        /// 获取连接字符串
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                string _connectionString = Util.ConnectionStrings("oleDB");
                string ConStringEncrypt = Util.AppSettings("crypt").ToLower();
                if (ConStringEncrypt == "yes")
                {
                    _connectionString = Util.Decrypt(_connectionString);
                }
                return Filter(_connectionString);
            }
        }

        public static string ConnectionStringByName(string name)
        {
            string _connectionString = Util.ConnectionStrings(name);
            string ConStringEncrypt = Util.AppSettings("crypt").ToLower();
            if (ConStringEncrypt == "yes")
            {
                _connectionString = Util.Decrypt(_connectionString);
            }
            return Filter(_connectionString);
        }

        /// <summary>
        /// 得到web.config里配置项的数据库连接字符串。
        /// </summary>
        /// <param name="configName"></param>
        /// <returns></returns>
        public static string GetConnectionString(string configName)
        {
            string connectionString = Util.ConnectionStrings(configName);
            string ConStringEncrypt = Util.AppSettings("crypt").ToLower();
            if (ConStringEncrypt == "yes")
            {
                connectionString = Util.Decrypt(connectionString);
            }
            return Filter(connectionString);
        }

        /// <summary>
        /// 过滤Provider
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        private static string Filter(string connectionString)
        {
            if (connectionString.Contains("Provider="))
            {
                string[] cons = connectionString.Split(';');

                connectionString = string.Empty;
                foreach (string str in cons)
                {
                    if (str.Contains("Provider=")) continue;
                    connectionString += str + ";";
                }
            }

            return connectionString;
        }
    }
}
